//
//  ZYLockTest.m
//  OC_Principle
//
//  Created by wangzhipan on 2025/2/16.
//

#import "ZYLockTest.h"
#import <os/lock.h>
#import <pthread/pthread.h>

@implementation ZYLockTest

- (void)failLock
{
    os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;
    
    //加锁
    os_unfair_lock_lock(&lock);
    
    //解锁
    os_unfair_lock_unlock(&lock);
}


/*
 pthread互斥锁
 */
+ (pthread_mutex_t)getPthread_mutex
{
    static pthread_mutex_t mutex;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pthread_mutexattr_t attr;
        pthread_mutexattr_init(&attr);
        //互斥锁
        pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
        pthread_mutex_init(&mutex, &attr);
        
        //销毁属性
        pthread_mutexattr_destroy(&attr);
    });
    return mutex;
}

+ (void)pthread_mutex_lock
{
    pthread_mutex_t mutex = [self getPthread_mutex];
    pthread_mutex_lock(&mutex);
}

+ (void)pthread_mutex_unlock
{
    pthread_mutex_t mutex = [self getPthread_mutex];
    pthread_mutex_unlock(&mutex);
}

/*
 pthread递归锁：
    允许同一个线程对一把锁进行重复加锁
    原理：同一个线程多次调用加锁api，，不造成休眠等待
    不同线程才会等待
 */
+ (pthread_mutex_t)get_pthread_recursive
{
    static pthread_mutex_t recursive;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pthread_mutexattr_t attr;
        pthread_mutexattr_init(&attr);
        //设置递归锁
        pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&recursive, &attr);
        
        //销毁属性
        pthread_mutexattr_destroy(&attr);
    });
    return recursive;
    
}

+ (void)pthread_recursive_lock
{
    pthread_mutex_t recursive = [self get_pthread_recursive];
    pthread_mutex_lock(&recursive);
}

+ (void)pthread_recursive_unlock
{
    pthread_mutex_t recursive = [self get_pthread_recursive];
    pthread_mutex_unlock(&recursive);
}





- (void)setup
{
    
}


@end
